package com.econ.powercloud.ems.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.*;

@Component
public class ApplicationContextConfiguration implements ApplicationContextAware {

    private static final List<Class> PRIMARY_CLASS = Arrays.asList(Integer.class, Boolean.class,
            Double.class, Byte.class, Short.class, Long.class, Float.class, BigDecimal.class, String.class);

    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextConfiguration.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public static <T> Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    public static Method getMethod(Class<?> proxyObject, String methodName) {
        Method[] methods = proxyObject.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                return method;
            }
        }
        return null;
    }

    /**
     * 获取类型实例
     * @param parameterType
     * @return
     */
    private static Object getInstance(Class<?> parameterType) throws Exception {
        if (parameterType.isAssignableFrom(List.class)) {
            return new ArrayList<>();
        } else if (parameterType.isAssignableFrom(Map.class)) {
            return new HashMap<>();
        } else if (parameterType.isAssignableFrom(Set.class)) {
            return new HashSet<>();
        }
        return parameterType.newInstance();
    }
}
